﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using UIShare;
using EFong.View.Proxy;
using EFong.View.HotelBooking;
using EFong.View.Customer;
using DevExpress.XtraLayout.Utils;
using EFong.View.Base;

namespace EFong.View.TrainTicket
{
    public partial class Frm_TrainTicket : BasicMdiChildForm
    {
        private Proxy.BusinessServiceProxy _businessProxy {get{ return Proxy.BusinessServiceProxy.GetInstance();}}
        private Proxy.PrintServiceProxy _printServiceProxy { get { return Proxy.PrintServiceProxy.GetInstance(); } }
        private Proxy.MasterServiceProxy _masterProxy {get{ return Proxy.MasterServiceProxy.GetInstance();}}

        public Frm_TrainTicket()
        {
            InitializeComponent();

            spe_PrintTotalPrice.SetValue(null);

            rad_SCustomer.SetValue(false);
            rad_SOrderDate.SetValue(false);
            rad_SOrderRef.SetValue(false);
            rad_SVendor.SetValue(false);

            this.layoutControlItem15.Visibility = this.layoutControlItem16.Visibility = LayoutVisibility.Never;

            this.bbt_Void.Visibility = AppParameters.IsAdRole ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
        }

        protected override void InitFields()
        {
        }

        protected override void Events()
        {
            this.gv_Orders.FocusedRowChanged += (s, e) =>
            {
                Contract.RTrainTicketOrder order = this.gv_Orders.GetRow(e.FocusedRowHandle) as Contract.RTrainTicketOrder;

                if (order != null)
                {
                    Order = _businessProxy.GetTrainTicketOrderByID(order.ID).ReturnValue;
                }
                else
                {
                    Order = null;
                }
            };

            this.gv_Details.FocusedRowChanged += (s, e) =>
            {
                Detail = this.gv_Details.GetRow(e.FocusedRowHandle) as Contract.TrainTicketOrderDetail; ;
            };

            this.btn_CustomerData.Click += (s, e) =>
            {
                browserCustomerData();
            };
            this.btn_Search.Click += (s, e) =>
            {
                searchOrders();
            };
            this.btn_Clear.Click += (s, e) =>
            {
                clearSearchConditions();
            };

            this.ckb_IsToHK.CheckedChanged += (s, e) =>
            {
                bool isToHK = this.ckb_IsToHK.GetValue();

                this.layoutControlItem15.Visibility = this.layoutControlItem16.Visibility = isToHK ? LayoutVisibility.Always : LayoutVisibility.Never;

                this.lct_VendorPrice.Text = isToHK ? "结算价" : "工本费";
            };
        }

        protected override void LoadDatas()
        {
            //this.cmb_SearchCustomer.Properties.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            //this.cmb_SearchVendor.Properties.BindingData(_masterProxy.GetAllTrainVendor().ReturnValue);
            bds_Customer.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            bds_Vendor.BindingData(_masterProxy.GetAllTrainVendor().ReturnValue);

            //bds_TrainTicketOrder.BindingData(new List<Contract.RTrainTicketOrder>());

            clearSearchConditions();

            SetAuthorities();
        }

        protected void SetAuthorities()
        {
            foreach (Contract.RoleAuthorizedItem roleAuthorizedItem in AppParameters.LoginUser.Role.Authorities)
            {
                switch (roleAuthorizedItem.AuthorizedItem.Name)
                {
                    case "火车票预定":
                        bbt_Add.Enabled = roleAuthorizedItem.Allow;
                        bbt_Edit.Enabled = roleAuthorizedItem.Allow;
                        break;
                    case "高级修改":
                        bbt_Void.Enabled = roleAuthorizedItem.Allow;
                        break;
                }
            }
        }

        private void bar_Main_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "bbt_Add":
                    this.add();
                    break;
                case "bbt_Edit":
                    this.edit();
                    break;
                case "bbt_Void":
                    this.voidOrder();
                    break;
                case "bbt_Print":
                    this.printOrder();
                    break;
                case "bbt_Close":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        private void printOrder()
        {
            if (Order == null)
                return;

            BasicPrinterForm frm = new BasicPrinterForm();
            frm.Text = "打印订单";

            Print.Rpt_TrainTicket report = new Print.Rpt_TrainTicket();
            report.Order = _printServiceProxy.GetPrintTrainOrder(Order.ID).ReturnValue;

            frm.Report = report;

            FormOpener.ShowDialog(frm);
        }

        private void voidOrder()
        {
            bool isSure = false;
            MsgBox.Question("确定将订单作废?", () => { isSure = true; }, null);
            if (!isSure)
                return;

            if (Order == null)
                return;

            Frm_Void frm = new Frm_Void(Order);
            frm.Text = "订单作废";
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
                searchOrders();
        }

        private void add()
        {
            Frm_TrainTicketEdit frm = new Frm_TrainTicketEdit();
            frm.Text = "增加订单";
            frm.ViewState = ViewStates.ADD;
            frm.Load += (s, e) =>
            {
                frm.Order = new Contract.TrainTicketOrder();
            };
            FormOpener.ShowDialog(frm);

            if (frm.ReturnValue != null && this.bds_TrainTicketOrder.DataSource is List<Contract.RTrainTicketOrder>)
            {
                this.bds_TrainTicketOrder.Insert(0, frm.ReturnValue);
            }
        }

        private void edit()
        {
            if (Order == null)
                return;
            if (Order.Status == MsgResource.VoidStatus)
                return;

            Frm_TrainTicketEdit frm = new Frm_TrainTicketEdit();
            frm.Text = "修改订单资料";
            frm.ViewState = ViewStates.EDIT;
            frm.ChangedOrReturnedAction = () => { updateReturn(); };
            frm.Load += (s, e) =>
            {
                frm.Order = Order;
            };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                this.gv_Orders.BeginUpdate();
                this.gv_Orders.EndUpdate();
                Order = frm.Order;
            }
        }


        private void browserCustomerData()
        {
            if (Order == null)
                return;

            Frm_CustomerEdit frm = new Frm_CustomerEdit();
            frm.Text = "客户详细资料";
            frm.ViewState = ViewStates.BROWSER;
            frm.Load += (s, e) =>
            {
                frm.CurCust = Order.Customer;
            };
            FormOpener.ShowDialog(frm);
        }

        private void searchOrders()
        {
            List<Contract.RTrainTicketOrder> trainTicketSource = new List<Contract.RTrainTicketOrder>();

            if (rad_SCustomer.Checked)
            {
                trainTicketSource = _businessProxy.GetTrainTicketOrderByCustomer(this.cmb_SearchCustomer.GetValue() as Contract.RCustomer).ReturnValue;
            }
            else if (rad_SOrderDate.Checked)
            {
                trainTicketSource = _businessProxy.GetTrainTicketOrderByOrderDate(this.dte_SearchStartDate.GetValue(AppParameters.FetureDateTime), this.dte_SearchEndDate.GetValue(AppParameters.FetureDateTime).AddDays(1)).ReturnValue;
            }
            else if (rad_SOrderRef.Checked)
            {
                trainTicketSource = _businessProxy.GetTrainTicketOrderByRef(this.txt_SearchOrderRef.GetText()).ReturnValue;
            }
            else if (rad_SVendor.Checked)
            {
                trainTicketSource = _businessProxy.GetTrainTicketOrderByVendor(this.cmb_SearchVendor.GetValue() as Contract.RVendor).ReturnValue;
            }
            else 
            {
                trainTicketSource = _businessProxy.GetAllTrainTicketOrder().ReturnValue;
            }

            bool sourceIsNull = trainTicketSource == null;
            bool sourceIsEmpty = !sourceIsNull && trainTicketSource.Count == 0;

            if (sourceIsEmpty)
            {
                MsgBox.Info("没有找到符合条件的订单.");
                this.Order = null;
                this.bds_TrainTicketOrder.BindingData(new List<Contract.RTrainTicketOrder>());
            }
            else
            {
                foreach (var order in trainTicketSource)
                {
                    if (order.Status == "已作废") 
                        order.CustomerStatus = "已作废";
                }

                this.bds_TrainTicketOrder.BindingData(trainTicketSource);
            }
        }

        private void clearSearchConditions()
        {
            this.rad_SCustomer.SetValue(false);
            this.rad_SOrderDate.SetValue(false);
            this.rad_SOrderRef.SetValue(false);
            this.rad_SVendor.SetValue(false);
            ControlExtensions.ClearValue(
                this.cmb_SearchCustomer,
                this.cmb_SearchVendor,
                this.dte_SearchEndDate,
                this.dte_SearchStartDate,
                this.txt_SearchOrderRef
                );

            searchOrders();
        }

        #region Order
        //selected TrainTicketOrder
        private Contract.TrainTicketOrder _order;
        public Contract.TrainTicketOrder Order
        {
            get { return _order; }
            set
            {
                _order = value;
                onOrderChanged();
            }
        }

        private void onOrderChanged()
        {
            if (Order == null)
            {
                ControlExtensions.ClearValue(
                        txt_OrderUser,
                        dte_OrderDate,
                        txt_Customer,
                        txt_OrderRef,
                        txt_Vendor,
                        txt_CreditTerm,
                        txt_VendorCurrency,
                        spe_ExchangeRate,
                        spe_PrintTotalPrice,
                        txt_OrderRemark,
                        dte_ProvideTicketDate,
                        dte_DeliveryTicketDate,
                        //txt_PaymentType,
                        //txt_BankAccount,
                        txt_VendorCurrency,
                        txt_OrderTotalPrice,
                        txt_OrderTotalProfit,
                        txt_OrderTotalVendorPrice,
                        txt_CPerson,
                        txt_CPersonPhone,
                        txt_CPersonTel
                    );
                this.bds_trainTicketOrderDetail.BindingData(typeof(Contract.TrainTicketOrderDetail));

                this.bds_trainTicketReturn.BindingData(typeof(Contract.RTrainTicketReturn));
                updateReturn();
            }
            else
            {
                foreach (var detail in Order.Details)
                {
                    detail.TrainTicketOrder = Order;
                }

                this.txt_Address.SetText(Order.Address);
                this.txt_OrderUser.SetText(Order.OrderUser);
                this.dte_OrderDate.SetValue(Order.OrderDate);
                this.txt_OrderRef.SetText(Order.Ref);
                this.txt_Customer.SetText(Order.Customer);
                this.txt_Vendor.SetText(Order.Vendor);
                this.txt_CreditTerm.SetText(Order.CreditTerm);
                this.spe_ExchangeRate.SetValue(Order.ExchangeRate);
                this.spe_PrintTotalPrice.SetValue(Order.PrintTotalPrice);
                this.txt_OrderRemark.SetText(Order.Remark);

                //if (Order.Customer != null)
                //    this.txt_Address.SetText(Order.Customer.Address);

                this.txt_OrderTicketUser.SetText(Order.OrderTicketUser);
                this.txt_ProvideTicketUser.SetText(Order.ProvideTicketUser);

                this.dte_ProvideTicketDate.SetValue(Order.ProvideTicketDate);
                this.dte_DeliveryTicketDate.SetValue(Order.DeliveryDate);

                //txt_PaymentType.SetText(Order.PaymentType);
                //txt_BankAccount.SetText(Order.BankAccount);
                if (Order.VendorCurrency != null)
                    this.txt_VendorCurrency.SetText(Order.VendorCurrency);

                this.txt_CPerson.SetText(Order.ContactPerson);
                this.txt_CPersonTel.SetText(Order.联系电话);
                this.txt_CPersonPhone.SetText(Order.移动电话);

                this.txt_OrderTotalPrice.SetText(Order.TotalPrice);
                this.txt_OrderTotalProfit.SetText(Order.TotalProfit);
                this.txt_OrderTotalVendorPrice.SetText(Order.TotalVendorPrice);

                this.bds_trainTicketOrderDetail.BindingData(Order.Details);


                this.bds_trainTicketReturn.BindingData(Order.TrainTicketReturnHis);
                updateReturn();
            }
        }

        private void updateReturn()
        {
            lcg_Return.Visibility = this.bds_trainTicketReturn.Count > 0 ? LayoutVisibility.Always : LayoutVisibility.Never;
        }
        #endregion

        #region Detail
        private Contract.TrainTicketOrderDetail _detail;
        public Contract.TrainTicketOrderDetail Detail
        {
            get { return _detail; }
            set
            {
                _detail = value;
                onDetailChanged();
            }
        }

        private void onDetailChanged()
        {
            if (Detail == null)
            {
                ControlExtensions.ClearValue(
                    dte_DepartDate,
                    txt_DepartTime,
                    txt_DepartLocation,
                    txt_Destination,
                    txt_TrainNo,
                    cmb_SeatType,
                    spe_TicketPrice,
                    spe_VendorPrice,
                    spe_DeliveryCost,
                    spe_Qty,
                    txt_TotalPrice,
                    txt_TotalVendorPrice,
                    txt_TotalProfit);
            }
            else
            {
                this.dte_DepartDate.SetValue(Detail.DepartDate);
                this.txt_DepartTime.SetText(Detail.出发时间);
                this.txt_DepartLocation.SetText(Detail.DepartLocation);
                this.txt_Destination.SetText(Detail.Destination);

                this.txt_TrainNo.SetText(Detail.TrainNo);
                this.cmb_SeatType.SetValue(Detail.SeatType);
                this.spe_TicketPrice.SetValue(Detail.TicketPrice);
                this.spe_VendorPrice.SetValue(Detail.VendorPrice);
                this.spe_DeliveryCost.SetValue(Detail.DeliveryCost);
                this.spe_Qty.SetValue(Detail.Qty);

                if (Detail.IsToHK && Detail.DepartLocation == Frm_TrainTicketDetailEdit.TRAIN_LOCATION_GZ)
                {
                    this.rad_Go.SetValue(true);
                }
                else if (Detail.IsToHK && Detail.DepartLocation == Frm_TrainTicketDetailEdit.TRAIN_LOCATION_HK)
                {
                    this.rad_Back.SetValue(true);
                }

                this.ckb_IsToHK.SetValue(Detail.IsToHK);

                this.txt_TotalPrice.SetText(Detail.TotalPrice);
                this.txt_TotalProfit.SetText(Detail.Profit);
                this.txt_TotalVendorPrice.SetText(Detail.TotalVendorPrice);
            }
        }
        #endregion
    }
}
